package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import com.zhentao.mapper.UserMapper;
import com.zhentao.utils.AppJwtUtil;
import com.zhentao.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @author 86191
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-04-27 09:27:39
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result loginOrReg(User user) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1==null){
            User user2=new User();
            user2.setUsername(user.getUsername());
            String salt = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 2);
//            BeanUtils.copyProperties();
            user2.setSalt(salt);
            String s = DigestUtils.md5DigestAsHex((salt + user.getPassword()).getBytes(StandardCharsets.UTF_8));
            user2.setPassword(s);
            userMapper.insert(user2);
            return Result.OK("注册成功",null);
        }
        String s = DigestUtils.md5DigestAsHex((user1.getSalt() + user.getPassword()).getBytes(StandardCharsets.UTF_8));
        if (s.equals(user1.getPassword())){
            String token = AppJwtUtil.getToken(user1.getUid().longValue());
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            return Result.OK("登录成功",map);
        }

        return Result.ERROR("登录失败",null);
    }
}




